﻿using Coldairarrow.Business.Base;
using Coldairarrow.Entity.Base;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.DTO;
using Coldairarrow.Entity.PB;
using Coldairarrow.IBusiness;
using Coldairarrow.Util;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace Coldairarrow.Api.Controllers.Base
{
    [Route("/Base/[controller]/[action]")]
    public class Base_DeviceController : BaseApiController
    {
        #region DI

        public Base_DeviceController(IBase_DeviceBusiness base_DeviceBus, IOperator Op, IOperatorDept Dept)
        {
            _base_DeviceBus = base_DeviceBus;
            _Op = Op;
            _Dept = Dept;
        }
        IOperator _Op { get; }
        IOperatorDept _Dept { get; }
        IBase_DeviceBusiness _base_DeviceBus { get; }

        #endregion

        #region 获取

        [HttpPost]
        public async Task<PageResult<Base_DeviceDTO>> GetDataList(PageInput<DeviceConditionDTO> input)
        {
            return await _base_DeviceBus.GetDataListAsync(input);
        }
        [HttpPost]
        public async Task<List<Base_DeviceDTO>> Selectid(string id)
        {
            var res = await _base_DeviceBus.Selectid(id);
            return res;
        }
        [HttpPost]
        public async Task<Base_Device> GetTheData(IdInputDTO input)
        {
            return await _base_DeviceBus.GetTheDataAsync(input.id);
        }

        #endregion

        #region 提交

        [HttpPost]
        public async Task SaveData(Base_Device data)
        {
            if (data.Id.IsNullOrEmpty())
            {
                InitEntity(data);

                await _base_DeviceBus.AddDataAsync(data);
            }
            else
            {
                await _base_DeviceBus.UpdateDataAsync(data);
            }
        }
        /// <summary>
        /// 获取操作者法人下的所有部门
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<List<Base_Department>> GetDetpList()
        {
            return await _base_DeviceBus.GetDetpListAsync();
        }
        /// <summary>
        /// 获取当前操作人法人下的所有车间
        /// </summary>
        /// <returns></returns>
        public async Task<List<Base_Department>> GetDetpListAsyncWorkShop()
        {
            return await _base_DeviceBus.GetDetpListAsyncWorkShop();
        }
        public async Task<List<Base_Department>> GetDetpListAsyncBumenis()
        {
            return await _base_DeviceBus.GetDetpListAsyncBumenis();
        }
        /// <summary>
        /// 获取当前操作人法人下的所有厂家
        /// </summary>
        /// <returns></returns>
        public async Task<List<Base_Department>> GetDetpListAsyncFatoc()
        {
            return await _base_DeviceBus.GetDetpListAsyncFatoc();
        }
        public async Task<List<Base_Department>> GetDetpListAsyncFatoc7()
        {
            return await _base_DeviceBus.GetDetpListAsyncFatoc7();
        }
        /// <summary>
        /// 生产设备导入  更新日期   2022/3/10 朱庆龙  完善设备导入验证
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        [NoCheckJWT]
        public async Task<AjaxResult> Import(IFormFile file)
        {
            string ReturnValue = string.Empty;
            bool flag = true;
            try
            {
                #region 检查文件
                string fileExt = Path.GetExtension(file.FileName).ToLower();
                var DataUser = new List<Base_Device>();//存储生产设备数据
                var liststr = new List<string>();
                MemoryStream ms = new MemoryStream();
                file.CopyTo(ms);
                ms.Seek(0, SeekOrigin.Begin);
                IWorkbook book;
                if (fileExt == ".xlsx")
                {
                    book = new XSSFWorkbook(ms);
                }
                else if (fileExt == ".xls")
                {
                    book = new HSSFWorkbook(ms);
                }
                else
                {
                    book = null;
                }
                ISheet sheet = book.GetSheetAt(0);

                int CountRow = sheet.LastRowNum + 1;//获取总行数

                if (CountRow - 1 == 0)
                {
                    return Error("Excel列表数据项为空!");
                }
                #endregion
                #region 循环验证
                for (int i = 1; i < CountRow; i++)
                {
                    //获取第i行的数据
                    var row = sheet.GetRow(i);
                    if (row != null)
                    {
                        //循环的验证单元格中的数据
                        for (int j = 0; j < 6; j++)
                        {
                            if ((j == 4 || j == 5) || (row.GetCell(j) == null || row.GetCell(j).ToString().Trim().Length == 0))
                            {
                                //return Error(ReturnValue += $"注意第{i + 1}行,第{j + 1}列数据为空。");
                            }
                            else
                            if (row.GetCell(j) == null || row.GetCell(j).ToString().Trim().Length == 0)
                            {
                                flag = false;
                                return Error(ReturnValue += $"第{i + 1}行,第{j + 1}列数据不能为空。");
                            }
                        }
                    }
                }
                #endregion
                #endregion
                if (flag)
                {

                    for (int i = 0; i < CountRow; i++)
                    {
                        if (i != 0)
                        {
                            ///创建设备对象
                            Base_Device Entity = new Base_Device();
                            var row = sheet.GetRow(i);

                            if (row.GetCell(0) != null && row.GetCell(0).ToString().Trim().Length > 0)
                            {
                                Entity.Id = IdHelper.GetId();
                                Entity.CreateTime = DateTime.Now;//当前系统时间
                                Entity.CreatorId = _Op.UserId;
                                Entity.Deleted = false;
                                Entity.Code = row.GetCell(0).ToString();
                                Entity.Mac = null;
                            }
                            if (row.GetCell(1) != null && row.GetCell(1).ToString().Trim().Length > 0)
                            {
                                Entity.Type = row.GetCell(1).ToString();
                            }
                            if (row.GetCell(2) != null && row.GetCell(2).ToString().Trim().Length > 0)
                            {
                                Entity.Name = row.GetCell(2).ToString();
                            }

                            if (row.GetCell(3) != null && row.GetCell(3).ToString().Trim().Length > 0)
                            {
                                Entity.Spec = row.GetCell(3).ToString();
                            }
                            else
                            {
                                Entity.Spec = null;
                            }

                            if (row.GetCell(4) != null && row.GetCell(4).ToString().Trim().Length > 0)
                            {

                                if (row.GetCell(4) == null && row.GetCell(4).ToString().Trim().Length == 0)
                                {
                                    Entity.ProcecureSubId = null;
                                }
                                else
                                {
                                    Entity.ProcecureSubId = row.GetCell(4).ToString();
                                }
                            }

                            if (row.GetCell(5) != null && row.GetCell(5).ToString().Trim().Length > 0)
                            {

                                if (row.GetCell(5) == null && row.GetCell(5).ToString().Trim().Length == 0)
                                {
                                    Entity.WorkShopId = null;
                                }
                                else
                                {
                                    Entity.WorkShopId = row.GetCell(5).ToString();
                                }
                            }
                            if (row.GetCell(6) != null && row.GetCell(6).ToString().Trim().Length > 0)
                            {
                                Entity.Position = row.GetCell(6).ToString();
                            }
                            else
                            {
                                Entity.Position = null;
                            }
                            if (row.GetCell(7) != null && row.GetCell(7).ToString().Trim().Length > 0)
                            {
                                Entity.State = false;
                                if (row.GetCell(7) == null && row.GetCell(7).ToString().Trim().Length == 0)
                                {
                                    Entity.State = false;
                                }

                                if ((row.GetCell(7).ToString() == "正常"))
                                {
                                    Entity.State = false;
                                }
                                if (row.GetCell(7).ToString() == "报废")
                                {
                                    Entity.State = true;
                                }
                            }
                            else {
                                Entity.State = false;
                            }

                            if (row.GetCell(8) != null && row.GetCell(8).ToString().Trim().Length > 0)
                            {
                                if (row.GetCell(8) == null && row.GetCell(4).ToString().Trim().Length == 0)
                                {
                                    Entity.DepartmentId = null;
                                }
                                else
                                {
                                    Entity.DepartmentId = row.GetCell(8).ToString();
                                }
                            }


                            if (row.GetCell(9) != null && row.GetCell(9).ToString().Trim().Length > 0)
                            {
                               if (row.GetCell(9) == null && row.GetCell(9).ToString().Trim().Length == 0)
                                {
                                    Entity.PersonId = null;
                                }
                                else
                                {
                                    Entity.PersonId = row.GetCell(9).ToString();
                                }
                            }
                        

                            DataUser.Add(Entity);
                            liststr.Add(Entity.Code);

                        }
                    }
                    var lists = _base_DeviceBus.GetQueryable<Base_Device>().Where(x => liststr.Contains(x.Code));
                    if (lists.Count() > 0)
                    {
                        liststr = liststr.Distinct<string>().ToList();
                        var result = String.Join(",", liststr.ToArray());
                        return Error(ReturnValue = "第" + CountRow + "行,设备编号" + result + "重复");
                    }
                    //判断导入的数据是否存在
                    var listContactsId = DataUser.Select(s => s.Type).Select(s => s.Trim()).Distinct().ToList();
                    var ProjectId = _base_DeviceBus.GetQueryable<Base_EnumItem>().Where(w => listContactsId.Contains(w.Name)).ToDictionary(k => k.Code, v => v.Name);
                    //判断工序存不存在 不存在则跳过 存在则验证
                    foreach (var item in DataUser)
                    {
                      

                        if (ProjectId.ContainsValue(item.Type.Trim()))
                        {
                            item.Type = ProjectId.FirstOrDefault(w => w.Value.Contains(item.Type.Trim())).Key;
                        }
                        else
                        {
                            return Error("设备类型不存在" + item.Type);
                        }
                        //验证工序
                        if (item.ProcecureSubId == null)
                        {
                            item.ProcecureSubId = null;
                        }
                        else
                        {
                            var listContactsId2 = DataUser.Select(s => s.ProcecureSubId).Select(s => s.Trim()).Distinct().ToList();
                            var ProjectId2 = _base_DeviceBus.GetQueryable<PB_ProcecureSub>().Where(w => listContactsId2.Contains(w.Name)).ToDictionary(k => k.Id, v => v.Name);
                            if (ProjectId2.ContainsValue(item.ProcecureSubId.Trim()))
                            {
                                item.ProcecureSubId = ProjectId2.FirstOrDefault(w => w.Value.Contains(item.ProcecureSubId.Trim())).Key;
                            }
                            else
                            {
                                return Error("工序不存在" + item.ProcecureSubId);
                            }
                        }
                        //验证车间
                        if (item.WorkShopId == null)
                        {
                            item.WorkShopId = null;
                        }
                        else
                        {
                            var listContactsId3 = DataUser.Select(s => s.WorkShopId).Select(s => s.Trim()).Distinct().ToList();
                            var ProjectId3 = _base_DeviceBus.GetQueryable<Base_Department>().Where(w => listContactsId3.Contains(w.Name)).ToDictionary(k => k.Id, v => v.Name);
                            if (ProjectId3.ContainsValue(item.WorkShopId.Trim()))
                            {
                                item.WorkShopId = ProjectId3.FirstOrDefault(w => w.Value.Contains(item.WorkShopId.Trim())).Key;
                              
                            }
                            else
                            {
                                return Error("车间不曾存在" + item.WorkShopId);
                            }
                        }
                        //验证部门
                        if (item.DepartmentId == null)
                        {
                            return Error("部门不能为空" );
                        }
                        else
                        {
                            var listContactsId4 = DataUser.Select(s => s.DepartmentId).Select(s => s.Trim()).Distinct().ToList();
                            var ProjectId4 = _base_DeviceBus.GetQueryable<Base_Department>().Where(w => listContactsId4.Contains(w.Name)).ToDictionary(k => k.Id, v => v.Name);
                            if (ProjectId4.ContainsValue(item.DepartmentId.Trim()))
                            {
                                item.DepartmentId = ProjectId4.FirstOrDefault(w => w.Value.Contains(item.DepartmentId.Trim())).Key;
                                var aa = await _Dept.GetOperatorGongChang(item.DepartmentId);
                                item.DeptId = aa.DetpId;
                                item.QrCode = "11" + "," + item.DeptId + "," + item.CreateTime.ToString("yyMMdd") + "," + item.Id;
                            }
                            else
                            {
                                return Error("部门不存在" + item.DepartmentId);
                            }
                        }
                        //验证保管人
                        if (item.PersonId == null)
                        {
                            item.PersonId = null;
                        }
                        else
                        {
                            var listContactsId5 = DataUser.Select(s => s.PersonId).Select(s => s.Trim()).Distinct().ToList();
                            var ProjectId5 = _base_DeviceBus.GetQueryable<Base_User>().Where(w => listContactsId5.Contains(w.RealName)).ToDictionary(k => k.Id, v => v.RealName);
                            if (ProjectId5.ContainsValue(item.PersonId.Trim()))
                            {
                                item.PersonId = ProjectId5.FirstOrDefault(w => w.Value.Contains(item.PersonId.Trim())).Key;
                            }
                            else
                            {
                                return Error("部负责人不存在" + item.PersonId);
                            }
                        }

                    }
                        if (DataUser.Count > 0)
                        {
                            try
                            {
                                await _base_DeviceBus.AddUserExlAsync(DataUser);

                            }
                            catch (Exception ex)
                            {
                                return Error("第" + CountRow + "行");
                            }
                            ReturnValue = $"数据导入成功,共导入{CountRow - 1}条数据。";

                        }
      
                    if (!flag)
                    {
                        return Error(ReturnValue = "数A据存在问题！" + ReturnValue);
                    }
                }
            }



            catch (Exception EX)
            {
                return Error("数据异常！");
            }
            return Success(ReturnValue);
        }
        [HttpPost]
        public async Task DeleteData(List<string> ids)
        {
            await _base_DeviceBus.DeleteDataAsync(ids);
        }
        /// <summary>
        /// 设备模板表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [NoCheckJWT]
        public IActionResult ExportToExcel()
        {
            //创建EXCEL工作薄
            IWorkbook workBook = new XSSFWorkbook();
            //创建sheet1文件表
            ISheet sheet = workBook.CreateSheet("设备信息模板表");
            var expDir = string.Format("{0}Export\\{1}", System.AppDomain.CurrentDomain.BaseDirectory,
                    DateTime.Now.ToString("yyyyMM"));

            if (!Directory.Exists(expDir)) Directory.CreateDirectory(expDir);

            string filePath = string.Format("生产设备模板表.xlsx", expDir, DateTime.Now.ToString("yyyyMMddHHmmss"));
            #region 创建Excel表头(sheet1)
            //创建表头
            IRow header = sheet.CreateRow(0);

            ICell cell = header.CreateCell(0);
            cell.SetCellValue("设备编号");
            cell = header.CreateCell(1);

            cell.SetCellValue("设备类型");
            cell = header.CreateCell(2);

            cell.SetCellValue("设备名称");
            cell = header.CreateCell(3);

            cell.SetCellValue("规格型号");
            cell = header.CreateCell(4);

            cell.SetCellValue("工序名称");
            cell = header.CreateCell(5);

            cell.SetCellValue("存放地点");
            cell = header.CreateCell(6);
            cell.SetCellValue("位置");

            cell = header.CreateCell(7);
            cell.SetCellValue("使用状态");
            cell = header.CreateCell(8);

            cell.SetCellValue("负责部门");
            cell = header.CreateCell(9);
            cell.SetCellValue("负责人");
            #endregion
            //工作流写入，通过流的方式进行创建生成文件
            using (MemoryStream stream = new MemoryStream())
            {
                workBook.Write(stream);
                byte[] buffer = stream.ToArray();
                return File(buffer, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", string.Format("生产设备模板表.xlsx", DateTime.Now.ToString("yyyyMMddHHmmss")));
            }

        }

    }
}